<%-- 
    Document   : index
    Created on : Nov 24, 2012, 1:23:51 PM
    Author     : kenisk
--%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="products" class="BLL.ProductBLL"/>
<% products.ProductsToXML(getServletContext().getRealPath("/") + "xml/products.xml");%>
<jsp:useBean id="categories" class="BLL.CategoryBLL"/>
<% categories.CategoriesToXML(getServletContext().getRealPath("/") + "xml/category.xml");%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>GiftShop</title>
        <link href="style.css" rel="stylesheet" type="text/css" />
    </head>
    <body>


        <table width="780" border="0" align="center" cellpadding="0" cellspacing="0">
            <tr>
            <a href="ProductController?Action=AllProduct">ALL PRODUCTS</a>
            <td class="logo_bg">
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td width="200" class="logo_bg"><a href="#"><img src="images/logo.jpg" width="225" height="79" alt=""	border="0" /></a></td>
                        <td align="right" valign="bottom" style="padding-bottom:3px;"><a href="#" class="top_link" >Contact Us |</a><a href="#" class="top_link">itemap</a></td>
                    </tr>
                </table>

            </td>

        </tr>

        <tr>
            <td>
                <img src="images/banner.jpg" width="780" height="333" alt=""/>

            </td>
        </tr>
        <tr>
            <td class="link_bg"><a href="#" class="link">Home</a> <a href="#" class="link">What's New? Specials</a>	<a href="#" class="link">Create an Account</a> <a href="#" class="link">Contact Us</a>
                <c:set var="data" value="${sessionScope.Username}" />

                <div id="login_box_content" style="z-index: 10000;">

                    <c:if test="${not empty data}">
                        <div id="login_form" style="float: right; font-size: medium; font-weight: bold">
                            Welcome: ${sessionScope.Username}
                        </div>
                    </c:if>

                    <c:if test="${empty data}">
                        <form action="UserController" id="login_form" method="post" style="float: right" onsubmit="return LoginValidate()">
                            <input id="Username" type="text" name="Username" placeholder="Username" onfocus="Username.value=''"/>
                            <input id="Password" type="password" name="Password"  placeholder="Password" onfocus="Password.value=''"/>
                            <input type="submit" value="Login" name="Action"/>
                        </form>
                    </c:if>
                    <div action="ProductController" id="login_form" method="post">
                        <input type="text" name="Search" id="Search" placeholder="Search By Name" onfocus="Search.value=''"/>
                        <input type="button" value="Search" onclick="Search()"/>
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td class="white"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr><div class="inner_copy"></div>
                    <td width="235" valign="top" style="padding:7px">
                        <table width="100%" border="0" cellspacing="0" cellpadding="0">
                            <tr>
                                <td class="heading_2">Categories</td>
                            </tr>
                            <c:import charEncoding="utf-8" url="XML/category.xml" var="xmlcdoc"/>
                            <c:import charEncoding="utf-8" url="xsl/category.xsl" var="xslcdoc"/>
                            <x:transform xml="${xmlcdoc}" xslt="${xslcdoc}"/>

                        </table>
                        <a id="cartShopping" onclick="viewCart()" href="#cart_info" name="modal" ondrop="drop(event)" ondragover="allowDrop(event)">
                            <strong id="numProduct">0</strong>
                            <img id="imag1" src="images/shopping_cart.png"/>
                            <strong id="totalPrice">0$</strong>
                        </a>
                    </td>
                    <td valign="top">
                        <div id="main-image" style="display: none" >
                            <div id="imgPrint">
                                <img src="images/print.png" onclick="exportPDF()">
                                <input type="submit" value="Continue Shopping" onclick="finishCheckout()">
                            </div>
                        </div>
                        <div id="main-checkout" style="width: 650px;display: none">
                            <table id="CheckoutDetail" style="width: 650px;">
                                <thead><tr><td>
                                            Delivery Info
                                        </td></tr></thead>
                                <tbody>
                                    <tr>
                                        <td>Name</td>
                                        <td><input type="text" id="NameReceiver" name="Name" value=""></td>
                                    </tr>
                                    <tr>
                                        <td>Address1</td>
                                        <td><input type="text" id="Address1" name="Address1" value=""></td>
                                    </tr>
                                    <tr>
                                        <td>Address2</td>
                                        <td><input type="text" id="Address2" name="Address2" value=""></td>
                                    </tr>
                                    <tr>
                                        <td>Phone</td>
                                        <td><input type="text" id="Phone" name="Phone" value=""></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div id="main-content" style="width:545px;  height: 545px; margin-top: 45px">
                            <c:import charEncoding="utf-8" url="XML/products.xml" var="xmldoc"/>
                            <c:import charEncoding="utf-8" url="xsl/products.xsl" var="xsldoc"/>
                            <x:transform xml="${xmldoc}" xslt="${xsldoc}"/>
                        </div>

                </table>
            </td>
        </tr>
    </table>
</body>
<div id="Detail-holder">

</div>
<div id="image-content">

</div>
<div id="Product-Detail"></div>
<script>


    document.getElementById("Product-Detail").style.display = 'none';

    function Category(id){     
        var imgTag=document.getElementById("main-image");
        var detail=document.getElementById("main-checkout");
        imgTag.style.display="none";
        detail.style.display= "none";
        var url = 'ProductController?Action=Category&Id='+id;
        xmlDomProduct = loadXML(url);
        transform('xsl/products.xsl',xmlDomProduct,'main-content');
       
    }


    var xmlDOM;
    var xmlDomProduct = loadXML('ProductController?Action=Search&name=');
    function validateDigits(event){   
        var key = event.charCode || event.keyCode || 0;
        // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
        if (key == 8 || key == 9 || key == 46 ||
            (key >= 37 && key <= 40) ||(key >= 48 && key <= 57) ||(key >= 96 && key <= 105)){
            return true;
        }
        return false;
    }

    function changeQty(productId,price){
        var quantity=document.getElementById('Quan'+productId).value;
        if (quantity==""||parseInt(quantity)==0){
            deleteProduct(productId);
        }else{
            updateQuantity(productId, price, quantity);
        }
        viewCart();
    }

    function viewCart(){
        xmlDOM=stringToXML(sessionStorage.xmldom);
        transform('xsl/cart.xsl',xmlDOM,'main-content');
        var detail=document.getElementById("main-checkout");
        detail.style.display= "";
    }
   

    function allowDrop(ev)
    {
        ev.preventDefault();
    }

    function drag(ev)
    {
        ev.dataTransfer.setData("product",ev.target.id);
    }

    function drop(ev)
    {
        ev.preventDefault();
        var product= document.getElementById(ev.dataTransfer.getData("product"));
        addToCart(product.getAttribute("productID"),product.getAttribute("productName"),
        product.getAttribute("productPrice"),1,product.getAttribute("src"));
    }

    function addToCart(productId,name,price,quantity,image){
        sessionStorage.numOfProduct = parseInt(sessionStorage.numOfProduct)+quantity;
        sessionStorage.totalPrice = parseFloat(sessionStorage.totalPrice)+(quantity*price);
        sessionStorage.xmldom ="<Product>";
        sessionStorage.xmldom +="<ProductID>"+productId+"</ProductID>";
        sessionStorage.xmldom +="<ProductName>"+name+"</ProductName>";   
        sessionStorage.xmldom +="<ProductPrice>"+price+"</ProductPrice>";
        sessionStorage.xmldom +="<ProductQty>"+quantity+"</ProductQty>";
        sessionStorage.xmldom +="<Subtotal>"+parseFloat(price)*parseFloat(quantity)+"</Subtotal>";
        sessionStorage.xmldom +="<ProductImage>"+image+"</ProductImage>";
        sessionStorage.xmldom +="</Product>";
        if(xmlDOM == null){
            sessionStorage.xmldom ='<Products>'+sessionStorage.xmldom+"</Products>";
            xmlDOM = stringToXML(sessionStorage.xmldom);
        }else{
            if(!checkExist(productId, price, quantity)){
                var childN = stringToXML(sessionStorage.xmldom).documentElement;
                xmlDOM.documentElement.appendChild(childN);
            }
        }
        sessionStorage.xmldom = convertText(xmlDOM);
        document.getElementById("numProduct").innerHTML = sessionStorage.numOfProduct;
        document.getElementById("totalPrice").innerHTML = sessionStorage.totalPrice + "$";
        //            loadXML('xsl/cart.xsl', function complete(xsltDOM) {
        //                transformXMLwithXSLT(xmlDOM,xsltDOM,'cart_content');
        //            });
    }

    loadCart();
    function loadCart(){
        if(sessionStorage.xmldom){
            xmlDOM = stringToXML(sessionStorage.xmldom);
            GetNumOfProduct(xmlDOM);
        }else{
            sessionStorage.numOfProduct = 0;
            sessionStorage.totalPrice = 0;
        }
        document.getElementById("numProduct").innerHTML = sessionStorage.numOfProduct;
        document.getElementById("totalPrice").innerHTML = sessionStorage.totalPrice + "$";
    }

    function GetNumOfProduct(doc){
        var childs = doc.firstChild.childNodes;
        sessionStorage.numOfProduct = 0;
        sessionStorage.totalPrice = 0;
        for(var i=0;i<childs.length;i++){
            var qtyNode = childs[i].firstChild.nextSibling.nextSibling.nextSibling;
            var subpriceNode = childs[i].firstChild.nextSibling.nextSibling.nextSibling.nextSibling;
            sessionStorage.numOfProduct = parseInt(sessionStorage.numOfProduct)+ parseInt(qtyNode.firstChild.nodeValue);
            sessionStorage.totalPrice = parseFloat(sessionStorage.totalPrice) + parseFloat(subpriceNode.firstChild.nodeValue)
        }
    }

    function updateQuantity(productId, price,quantity){
        if(xmlDOM != null){
            var childs = xmlDOM.firstChild.childNodes;
            for(var i=0;i<childs.length;i++){
                var proID = childs[i].firstChild.firstChild.nodeValue;
                if(proID == productId){
                    var nodeQty = childs[i].firstChild.nextSibling.nextSibling.nextSibling;
                    var qty = quantity;
                    nodeQty.firstChild.nodeValue = qty;
                    var nodeSubPrice = nodeQty.nextSibling;
                    nodeSubPrice.firstChild.nodeValue = parseFloat(price) * qty;
                    sessionStorage.xmldom = convertText(xmlDOM);
                    return true;
                }
            }
        }
        return false;
    }
    function deleteProduct(productId){
        xmlDOM==stringToXML(sessionStorage.xmldom);
        if(xmlDOM){
            var childs = xmlDOM.firstChild.childNodes;
            for(var i=0;i<childs.length;i++){
                var proID = childs[i].firstChild.firstChild.nodeValue;
                if(proID == productId){
                    xmlDOM.firstChild.removeChild(childs[i]);
                    sessionStorage.xmldom = convertText(xmlDOM);
                    if(xmlDOM.firstChild.childNodes.length == 0){
                        sessionStorage.numOfProduct = 0;
                        document.getElementById("numProduct").innerHTML = sessionStorage.numOfProduct;
                        document.getElementById('totalPrice').innerHTML = "0$";
                    }else{
                        loadCart();
                    }
                    return;
                }
            }
        }
    }

    function stringToXML(text){
        var doc;
        try{
            if(window.ActiveXObject){
                doc = new ActiveXObject("Microsoft.XMLDOM");
                doc.async = 'false';
                doc.loadXML(text);

            }else{
                var parser = new DOMParser();
                doc = parser.parseFromString(text,'text/xml')
            }
        }catch(e){
            doc.load(text);
        }
        return doc;
    }

    function convertText(doc){
        var xmlContent;
        try{
            if(window.ActiveXObject){
                xmlContent = doc.documentElement.xml;
            }else{
                xmlContent = new XMLSerializer().serializeToString(doc);
            }
            return xmlContent;
        }catch(e){
            return "";
            e.toString();
        }
    }

    function checkExist(productId, price,quantity){
        if(xmlDOM != null){
            var childs = xmlDOM.firstChild.childNodes;
            for(var i=0;i<childs.length;i++){
                var proID = childs[i].firstChild.firstChild.nodeValue;
                if(proID == productId){
                    var nodeQty = childs[i].firstChild.nextSibling.nextSibling.nextSibling;
                    var qty = parseInt(nodeQty.firstChild.nodeValue) + quantity;
                    nodeQty.firstChild.nodeValue = qty;
                    var nodeSubPrice = nodeQty.nextSibling;
                    nodeSubPrice.firstChild.nodeValue = parseFloat(price) * qty;
                    sessionStorage.xmldom = convertText(xmlDOM);
                    return true;
                }
            }
        }
        return false;
    }

    function GetXMLHttpObject()
    {
        try
        {
            xmlHttp= new ActiveXObject("Microsoft.XMLDOMTTP");
        }catch(e)
        {
            try{
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e)
            {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return xmlHttp;
    }
    function loadXML(serverMethod)
    {
        var xmlHttp=null;
        if (window.XMLHttpRequest)
          {
              xmlHttp=new XMLHttpRequest();
          }
        else
          {
              xmlHttp=GetXMLHttpObject();
          }
        xmlHttp.open("GET",serverMethod,false);
        xmlHttp.send(null);
        return xmlHttp.responseXML;
    }

    function transform (xsltFile,xmlDOM,idvalue){
        if(window.ActiveXObject)
        {
            var xsltDOM = new ActiveXObject ("Microsoft.XMLDOM");
            xsltDOM.async = false;
            xsltDOM.load(xsltFile);
            var out = xmlDOM.transformNode(xsltDOM);
            document.getElementById(idvalue).innerHTML=out;
        }
        else{
            var xsltProcessor = new XSLTProcessor();
            xsl = loadXML(xsltFile);
            //                    xml = loadXMLAndXSL(xsltFile);
                    xsltProcessor.importStylesheet(xsl);
                    resultDocument = xsltProcessor.transformToFragment(xmlDOM, document);
            document.getElementById(idvalue).innerHTML="";
                    document.getElementById(idvalue).appendChild(resultDocument);
        }
    }

    function Search()
    {
        var value = document.getElementById('Search').value;
        var url = 'ProductController?Action=Search&name='+value;
        xmlDomProduct = loadXML(url);
        transform('xsl/products.xsl',xmlDomProduct,'main-content');
        var detail=document.getElementById("main-checkout");
        detail.style.display= "none";
        var imgTag=document.getElementById("main-image");
        imgTag.style.display= "none";
    }
    function CheckOut(){
        xmlString=sessionStorage.xmldom;
        var xmlHttp = false;
        if (window.XMLHttpRequest)
          {
              xmlHttp=new XMLHttpRequest();
          }
        else
          {
              xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
          }

        var name= document.getElementById("NameReceiver").value;
        var Address1= document.getElementById("Address1").value;
        var Address2=document.getElementById("Address2").value;
        var Phone=document.getElementById("Phone").value;
        xmlHttp.open("POST","CheckOutController?action=CheckOut&NameReceiver="+name+"&Address1="+Address1+"&Address2="+Address2+"&Phone="+Phone,true);

        xmlHttp.setRequestHeader("Content-Type", "text/xml;charset=UTF-8");

        xmlHttp.send(xmlString);

        xmlHttp.onreadystatechange = function()
        {
            //get response
            if(xmlHttp.readyState==4 && xmlHttp.status==200){
                var result = xmlHttp.responseText
                if(parseInt(result) >-1) //update success
                {
                    var infodetail= document.getElementById("main-checkout");
                    infodetail.style.display = 'none';
                    document.getElementById("main-content").innerHTML="";   
                    var imgTag=document.getElementById("main-image");
                    imgTag.style.display="";
                    sessionStorage.xmldom="";
                    xmlDOM=null;
                    sessionStorage.numOfProduct=0;
                    sessionStorage.totalPrice=0;
                    document.getElementById("numProduct").innerHTML = sessionStorage.numOfProduct;
                    document.getElementById('totalPrice').innerHTML = sessionStorage.totalPrice+"$";
                    sessionStorage.currentOrder=parseInt(result);
                    alert("Success");
                }
                else{
                    alert("Not Success! Some products are sold out")
                }
            }
        }
    }

    function finishCheckout(){
        var imgTag=document.getElementById("main-image");
        imgTag.style.display = 'none';
    }


    function ContinueShopping(){
        var infodetail= document.getElementById("CheckoutDetail");
        infodetail.style.visibility= 'hidden';
        infodetail.style.display = 'none';
        document.getElementById('Detail-holder').appendChild(infodetail);
        document.getElementById("main-content").innerHTML="";
    }



    function productonmouseover(id) {
        
        var childs;
        if(xmlDomProduct != null){
            childs = xmlDomProduct.childNodes;
            for(var i=0;i<childs.length;i++){
                if(childs[i].nodeName=='Products'){
                    childs = childs[i].childNodes;
                    break;
                }
            }
            for(var i=0;i<childs.length;i++){
                var childs2 = childs[i].childNodes;
                for(var j = 0; j<childs2.length;j++){
                    if(childs2[j].nodeName=='ProductID'){
                        if(childs2[j].textContent==id){
                            domxml = childs[i];
                            break;
                        }else{
                            continue;
                        }
                    }
                }
            }

        }
        domxml =  stringToXML(convertText(domxml));
        if(domxml!=null){
            transform('xsl/productDetail.xsl',domxml,'Product-Detail');
            document.getElementById("Product-Detail").style.display = '';
            document.getElementById("Product-Detail").style.left = x+'px';
            document.getElementById("Product-Detail").style.top = y+'px';
        }else{
            document.getElementById("Product-Detail").style.display = 'none';
        }
    }

    function productonmouseout(){
        document.getElementById("Product-Detail").style.display = 'none';
    }
    var x=0,y=0;
    function getMousePosition(e)
    {
        return e.pageX ? {'x':e.pageX, 'y':e.pageY} : {'x':e.clientX + document.documentElement.scrollLeft + document.body.scrollLeft, 'y':e.clientY + document.documentElement.scrollTop + document.body.scrollTop};
    }

    function showMousePos(e)
    {
        if (!e) e = event; // make sure we have a reference to the event
        var mp = getMousePosition(e);
        x=mp.x;
        y=mp.y;
        document.getElementById("Product-Detail").style.left = x+'px';
        document.getElementById("Product-Detail").style.top = y+'px';
        
    }
    function init()
    {
        document.onmousemove = showMousePos;
    }
    var detailId = 0;
    document.onmousemove=init;

    function exportPDF(){
        loadXML("ConvertPDFServer?id="+sessionStorage.currentOrder);
    }

    function LoginValidate()
    {
        var username = document.getElementById('Username').value;
        var pass = document.getElementById('Password').value;
        if(username.length<1){
                return false;
            }
        if(pass.length<0) {
            return false
        }
        return true;
    }

    function PriceValidate(){
        
    }
</script>
</html>